package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.TimerSettingsMapper;
import com.example.demo.model.entity.TimerSettings;
import com.example.demo.service.TimerTaskService;
import com.example.demo.model.common.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/timer")
public class TimerController {

    @Autowired
    private TimerSettingsMapper timerSettingsMapper;

    @Autowired
    private TimerTaskService timerTaskService;

    @PostMapping("/save")
    public ApiResult<Void> saveTimerSettings(@RequestBody Map<String, Object> timerSettingsMap) {
        try {
            String imei = (String) timerSettingsMap.get("imei");
            String productId = (String) timerSettingsMap.get("productId");

            saveOrUpdateTimerSettings(imei, productId, "main", (Map<String, Object>) timerSettingsMap.get("main"));
            saveOrUpdateTimerSettings(imei, productId, "relay1", (Map<String, Object>) timerSettingsMap.get("relay1"));
            saveOrUpdateTimerSettings(imei, productId, "relay2", (Map<String, Object>) timerSettingsMap.get("relay2"));

            timerTaskService.refreshTimerTasks();
            return ApiResult.success();
        } catch (Exception e) {
            return ApiResult.error("保存定时器设置失败：" + e.getMessage());
        }
    }

    @GetMapping("/get")
    public ApiResult<Map<String, Object>> getTimerSettings(@RequestParam("imei") String imei, @RequestParam("productId") String productId) {
        System.out.println("收到的请求参数 - IMEI: " + imei + ", ProductID: " + productId);

        try {
            QueryWrapper<TimerSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("imei", imei).eq("product_id", productId);
            List<TimerSettings> settingsList = timerSettingsMapper.selectList(queryWrapper);

            if (!settingsList.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("imei", imei);
                response.put("productId", productId);

                for (TimerSettings settings : settingsList) {
                    Map<String, Object> settingsMap = new HashMap<>();
                    settingsMap.put("enabled", settings.getEnabled());
                    settingsMap.put("onTime", settings.getOnTime());
                    settingsMap.put("offTime", settings.getOffTime());
                    settingsMap.put("repeat", settings.getRepeat());
                    response.put(settings.getRelayType(), settingsMap);
                }

                System.out.println("返回给前端的数据: " + response);
                return ApiResult.success(response);
            } else {
                System.out.println("未找到定时器设置数据");
                return ApiResult.error("未找到定时器设置数据");
            }
        } catch (Exception e) {
            return ApiResult.error("获取定时器设置失败：" + e.getMessage());
        }
    }

    private void saveOrUpdateTimerSettings(String imei, String productId, String relayType, Map<String, Object> settingsMap) {
        QueryWrapper<TimerSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("imei", imei)
                .eq("product_id", productId)
                .eq("relay_type", relayType);

        TimerSettings settings = timerSettingsMapper.selectOne(queryWrapper);

        if (settings == null) {
            settings = new TimerSettings();
            settings.setImei(imei);
            settings.setProductId(productId);
            settings.setRelayType(relayType);
        }

        settings.setEnabled((Boolean) settingsMap.get("enabled"));
        settings.setOnTime((String) settingsMap.get("onTime"));
        settings.setOffTime((String) settingsMap.get("offTime"));
        settings.setRepeat((String) settingsMap.get("repeat"));

        if (settings.getId() == null) {
            timerSettingsMapper.insert(settings);
        } else {
            timerSettingsMapper.updateById(settings);
        }
    }
}